#include "config.h"
#include "debug.h"
#include "volt_sensor_state.h"
#include "standby_state.h"


extern standby_state standby_s;
extern volt_sensor_state volt_sensor_s;


volt_sensor_state::volt_sensor_state(int in) 
: input_pin(in),
   samples(),
   sample_index(0),
   sample_min(~0),
   sample_max(0),
   sample_high_count(0),
   last_zero_at(0)
{
}


void volt_sensor_state::on_enter()
{
   DEBUG_PRINTLN("volt_sensor_state: entering volt-sensor");

   pinMode(status_green_pin, OUTPUT);
   pinMode(status_red_pin, OUTPUT);
   pinMode(speaker_pin, OUTPUT);
   digitalWrite(status_green_pin, LOW);
   digitalWrite(status_red_pin, LOW);
   noTone(speaker_pin);
}


void volt_sensor_state::on_update()
{
   samples[sample_index] = analogRead(input_pin);

   // res: What are we doing with this?
   if (samples[sample_index] == 0) {
      last_zero_at = millis();
   }

   sample_min = min(sample_min, samples[sample_index]);
   sample_max = max(sample_max, samples[sample_index]);

   ++sample_index;

   if (sample_index == samples_size) {
      DEBUG_PRINT("volt_sensor_state: min = ");
      DEBUG_PRINTDEC(sample_min);
      DEBUG_PRINT(",  max = ");
      DEBUG_PRINTDEC(sample_max);
      DEBUG_PRINT(",  threshold = ");
      DEBUG_PRINTDEC(sample_range_threshold);
      DEBUG_PRINTLN();

      if ((sample_max - sample_min) > sample_range_threshold) {
         ++sample_high_count;
      }
      else {
         digitalWrite(status_red_pin, LOW);
         digitalWrite(status_green_pin, HIGH);
         sample_high_count = 0;
      }

      if (sample_high_count > sample_high_threshold) {
         digitalWrite(status_green_pin, LOW);
         digitalWrite(status_red_pin, HIGH);
         tone(speaker_pin, speaker_freq, speaker_time);
      }

      sample_index = 0;
      sample_min = ~0;
      sample_max = 0;
   }
}


void volt_sensor_state::on_leave()
{
   digitalWrite(status_green_pin, LOW);
   digitalWrite(status_red_pin, LOW);
   noTone(speaker_pin);

   DEBUG_PRINTLN("volt_sensor_state: leaving volt-sensor");
}

